import Vue from 'vue';
import Router from 'vue-router';
import Cookie from 'js-cookie';
import shareJs from "util/shareJs";

import {
	sessionSetItem,
	sessionGetItem,
	sessionRemoveItem
} from 'util/index.js';

import {
	getAuth
} from 'util/getAuth.js';

Vue.use(Router)
let routes = []
const routerContext = require.context('./', true, /index\.js$/)
routerContext.keys().forEach(route => {
	// 如果是根目录的index.js不处理
	if (route.startsWith('./main')) {
		return
	}
	const routerMoudule = routerContext(route)
	routes = [...routes, ...(routerMoudule.default || routerMoudule)]

})

routes.forEach(route => {
	route.path = route.path || '/' + (route.name || '');
});

const router = new Router({
	mode: 'history',
	routes,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition
		} else {
			return {
				x: 0,
				y: 0
			}
		}
	}
});

// beforeRouter ()

function beforeRouter () {
	router.beforeEach((to, from, next) => {
		const token = sessionGetItem('token');
		// 添加标题
		if (to.meta.title) {
			document.title = to.meta.title;
		}
		if (to.meta.noAuth) {
			console.log(`router跳转前拦截不需要验证token是否存在`);
			next();
		} else {
			// 如果token存在
			if (token) {
				console.log(`router跳转前拦截token存在`);
				next();
			} else {
				console.log(`router跳转前拦截token不存在，跳转到init页，fullpath为${to.fullPath}`);
				let redirect = to.fullPath;
				if (redirect) {
					console.log('redirect存在，重新授权，执行getAuth方法');
					getAuth(redirect);
				}
			}
		}
	});
}
export default router
